const express = require('express');
const router = express.Router();
const Medicine = require('../models/medicine.model');
const Category = require('../models/category.model');
const asyncHandler = require('express-async-handler');
const auth = require('../middleware/auth');

// 获取药品列表
router.get('/', auth, asyncHandler(async (req, res) => {
  const { categoryId, keyword, status, page = 1, limit = 10 } = req.query;
  const query = { userId: req.user.id };

  if (categoryId) query.categoryId = categoryId;
  if (status) query.status = status;
  if (keyword) query.name = { $regex: keyword, $options: 'i' };

  const skip = (page - 1) * limit;
  
  const [medicines, total] = await Promise.all([
    Medicine.find(query)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(Number(limit))
      .populate('categoryId', 'name'),
    Medicine.countDocuments(query)
  ]);

  res.json({
    success: true,
    data: {
      medicines,
      total,
      page: Number(page),
      totalPages: Math.ceil(total / limit)
    }
  });
}));

// 获取药品详情
router.get('/:id', auth, asyncHandler(async (req, res) => {
  const medicine = await Medicine.findOne({
    _id: req.params.id,
    userId: req.user.id
  }).populate('categoryId', 'name');

  if (!medicine) {
    res.status(404);
    throw new Error('药品不存在');
  }

  res.json({
    success: true,
    data: medicine
  });
}));

// 创建药品
router.post('/', auth, asyncHandler(async (req, res) => {
  const medicine = await Medicine.create({
    ...req.body,
    userId: req.user.id
  });

  res.status(201).json({
    success: true,
    data: medicine
  });
}));

// 更新药品
router.put('/:id', auth, asyncHandler(async (req, res) => {
  const medicine = await Medicine.findOneAndUpdate(
    { _id: req.params.id, userId: req.user.id },
    req.body,
    { new: true, runValidators: true }
  );

  if (!medicine) {
    res.status(404);
    throw new Error('药品不存在');
  }

  res.json({
    success: true,
    data: medicine
  });
}));

// 删除药品
router.delete('/:id', auth, asyncHandler(async (req, res) => {
  const medicine = await Medicine.findOneAndDelete({
    _id: req.params.id,
    userId: req.user.id
  });

  if (!medicine) {
    res.status(404);
    throw new Error('药品不存在');
  }

  res.json({
    success: true,
    data: {}
  });
}));

// 获取分类列表
router.get('/categories/list', auth, asyncHandler(async (req, res) => {
  const categories = await Category.find({ userId: req.user.id })
    .sort({ order: 1, createdAt: -1 });

  res.json({
    success: true,
    data: categories
  });
}));

// 创建分类
router.post('/categories', auth, asyncHandler(async (req, res) => {
  const category = await Category.create({
    ...req.body,
    userId: req.user.id
  });

  res.status(201).json({
    success: true,
    data: category
  });
}));

// 更新分类
router.put('/categories/:id', auth, asyncHandler(async (req, res) => {
  const category = await Category.findOneAndUpdate(
    { _id: req.params.id, userId: req.user.id },
    req.body,
    { new: true, runValidators: true }
  );

  if (!category) {
    res.status(404);
    throw new Error('分类不存在');
  }

  res.json({
    success: true,
    data: category
  });
}));

// 删除分类
router.delete('/categories/:id', auth, asyncHandler(async (req, res) => {
  const category = await Category.findOneAndDelete({
    _id: req.params.id,
    userId: req.user.id
  });

  if (!category) {
    res.status(404);
    throw new Error('分类不存在');
  }

  // 将该分类下的药品移动到默认分类
  await Medicine.updateMany(
    { categoryId: req.params.id },
    { categoryId: null }
  );

  res.json({
    success: true,
    data: {}
  });
}));

module.exports = router;